extends Node2D
class_name SyncPlayer

var current_name : String = "sync"
var current_scene
var current_index : int

func _ready() -> void:
	current_scene = get_tree().current_scene

func _move_to(target_dir : Vector2, wait_time : float = 1.0) -> bool :
	var result = _move_to_ing(target_dir, wait_time)
	if result : return true
	var ori_pos = global_position
	var tween = create_tween()
	tween.tween_property(self, "global_position", global_position + target_dir * 30.0, wait_time/4.0)
	tween.tween_callback(
		func() :
			var tw = create_tween()
			tw.tween_property(self, "global_position", ori_pos, wait_time/4.0)
			)
	return result

func _move_to_ing(target_dir : Vector2, wait_time : float = 1.0) -> bool :
	var base_grid = current_scene.base_grid
	var new_index = current_index + target_dir.y * base_grid.grid_xy.x + target_dir.x
	var cells = base_grid.get_children()
	if new_index < 0 or cells.size() <= new_index : return false
	var cell = cells.get(new_index)
	if cell :
		if cell._not_pass_by_role(current_name) : return false
		if (cell.global_position - global_position).length() > base_grid.cell_size.length() : return false
		current_index = cell.get_index()
		var tween = create_tween()
		tween.tween_property(self, "global_position", cell.global_position, wait_time)
		return true
	return false

func _get_next_cell(target_dir : Vector2) :
	var base_grid = current_scene.base_grid
	var current_cell = base_grid.get_children().get(current_index)
	var new_index = current_index + target_dir.y * base_grid.grid_xy.x + target_dir.x
	var cells = base_grid.get_children()
	var cell = cells.get(new_index)
	if cell :
		if cell._not_pass_by_role(current_name) : return current_cell
		return cell
	return current_cell
